package cn.mysite.mycompany.controller;


import cn.mysite.mycompany.entity.User;
import cn.mysite.mycompany.service.CartService;
import cn.mysite.mycompany.service.ProductCategoryService;
import cn.mysite.mycompany.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author  ChenChongFei
 * @since 2021-03-13
 */
@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private CartService cartService;

    @GetMapping("/list/{type}/{id}")
    public ModelAndView list(@PathVariable("type") String type, @PathVariable("id") Integer id,HttpSession session){
        ModelAndView mv = new ModelAndView();
        mv.addObject("productList",productService.findByCategoryId(type,id));
        mv.addObject("list",productCategoryService.getAllProductCategoryVo());
        //用户登陆时获取用户id返回购物车信息
        User user=(User)session.getAttribute("user");
        if(user!=null)
            mv.addObject("cartList", cartService.findAllCartVOByUserId(user.getId()));
        else
            mv.addObject("cartList",new ArrayList<>());
        mv.setViewName("productList");
        return mv;
    }

    @GetMapping("/findById/{id}")
    public ModelAndView findById(@PathVariable("id") Integer id, HttpSession session){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("productDetail");
        mv.addObject("product",productService.getById(id));
        mv.addObject("list",productCategoryService.getAllProductCategoryVo());
        //用户登陆时获取用户id返回购物车信息
        User user=(User)session.getAttribute("user");
        if(user!=null)
            mv.addObject("cartList", cartService.findAllCartVOByUserId(user.getId()));
        else
            mv.addObject("cartList",new ArrayList<>());
        return mv;
    }

}

